package les

class IndicacaoController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		
		List lista = Indicacao.list(params)
		if (params.buscaTudo) {
			lista = Indicacao.findAll
		}
		if (params.buscaNome && params.buscaNome != "") {
			lista = Indicacao.findAllByNomeIlike("%${params.buscaNome}%")
		}
		
        [indicacaoInstanceList: Indicacao.list(params), indicacaoInstanceTotal: Indicacao.count()]
    }

    def create = {
        def indicacaoInstance = new Indicacao()
        indicacaoInstance.properties = params
		
		Integrante coordenadorDeCirculo = Integrante.findByUsuario(session.usuarioLogado)
		
		ArrayList<Indicacao> indicacoesCirculo = new ArrayList<Indicacao>();
		
		List indicacoes = Indicacao.findAll();
		for (Indicacao i : indicacoes){
			Integrante integrante = i.integrante;
			
			if(coordenadorDeCirculo.ehCoordenadorDeCirculoDoIntegrante(integrante)){
				indicacoesCirculo.add(i);
			}
		}
		
		session.indicacoes = indicacoesCirculo 
        return [indicacaoInstance: indicacaoInstance]
    }

    def save = {
		Integrante integrante = Integrante.findByNome(params.indicarIntegrante)
		Equipe equipe = Equipe.findByNome(params.escolherEquipe)
        def indicacaoInstance = new Indicacao()
		indicacaoInstance.integrante = integrante
		indicacaoInstance.indicacao = equipe
        if (indicacaoInstance.save(flush: true)) {
            redirect(action: "create")
        }
        else {
            render(view: "create", model: [indicacaoInstance: indicacaoInstance])
        }
    }

    def show = {
        def indicacaoInstance = Indicacao.get(params.id)
        if (!indicacaoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'indicacao.label', default: 'Indicacao'), params.id])}"
            redirect(action: "list")
        }
        else {
            [indicacaoInstance: indicacaoInstance]
        }
    }

    def edit = {
        def indicacaoInstance = Indicacao.get(params.id)
        if (!indicacaoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'indicacao.label', default: 'Indicacao'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [indicacaoInstance: indicacaoInstance]
        }
    }

    def update = {
        def indicacaoInstance = Indicacao.get(params.id)
        if (indicacaoInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (indicacaoInstance.version > version) {
                    
                    indicacaoInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'indicacao.label', default: 'Indicacao')] as Object[], "Another user has updated this Indicacao while you were editing")
                    render(view: "edit", model: [indicacaoInstance: indicacaoInstance])
                    return
                }
            }
            indicacaoInstance.properties = params
            if (!indicacaoInstance.hasErrors() && indicacaoInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'indicacao.label', default: 'Indicacao'), indicacaoInstance.id])}"
                redirect(action: "show", id: indicacaoInstance.id)
            }
            else {
                render(view: "edit", model: [indicacaoInstance: indicacaoInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'indicacao.label', default: 'Indicacao'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def indicacaoInstance = Indicacao.get(params.id)
        if (indicacaoInstance) {
            try {
                indicacaoInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'indicacao.label', default: 'Indicacao'), params.id])}"
                redirect(action: "create")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'indicacao.label', default: 'Indicacao'), params.id])}"
                redirect(action: "create", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'indicacao.label', default: 'Indicacao'), params.id])}"
            redirect(action: "create")
        }
    }
	
	def pegarIntegrantesParaAdicionar = {
		Integrante coordenadorDeCirculo = Integrante.findByUsuario(session.usuarioLogado)
		
		List integrantes = Integrante.findAllByNomeIlike("%${params.query}%")

		ArrayList<Integrante> integrantesParaResposta = new ArrayList<Integrante>();
		for (Integrante integrante : integrantes) {
			if (coordenadorDeCirculo.ehCoordenadorDeCirculoDoIntegrante(integrante) && (Indicacao.findAllByIntegrante(integrante).size() == 0)) {
				integrantesParaResposta.add(integrante)
			}
		}
		
		// Criar resposta XML
		render(contentType: "text/xml") {
			results() {
				for (i in integrantesParaResposta) {
					String nome = "";
					nome = i.nome;
					result(name: nome, id: i.id)
				}
			}
		}
	}
	
	def pegarEquipesParaAdicionar = {
				
		List equipes = Equipe.findAllByNomeIlike("%${params.query}%")

		// Criar resposta XML
		render(contentType: "text/xml") {
			results() {
				for (e in equipes) {
					String nome = "";
					nome = e.nome;
					result(name: nome, id: e.id)
				}
			}
		}
	}
}
